@file:Suppress("UNCHECKED_CAST", "USELESS_CAST", "INAPPLICABLE_JVM_NAME", "UNUSED_ANONYMOUS_PARAMETER", "NAME_SHADOWING")
package uni.UNIB71475B
import io.dcloud.uniapp.*
import io.dcloud.uniapp.extapi.*
import io.dcloud.uniapp.framework.*
import io.dcloud.uniapp.runtime.*
import io.dcloud.uniapp.vue.*
import io.dcloud.uniapp.vue.shared.*
import io.dcloud.uts.*
import io.dcloud.uts.Map
import io.dcloud.uts.Set
import io.dcloud.uts.UTSAndroid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import io.dcloud.uniapp.extapi.base64ToArrayBuffer as uni_base64ToArrayBuffer
import io.dcloud.uniapp.extapi.createWebviewContext as uni_createWebviewContext
import io.dcloud.uniapp.extapi.downloadFile as uni_downloadFile
import io.dcloud.uniapp.extapi.env as uni_env
import io.dcloud.uniapp.extapi.getDeviceInfo as uni_getDeviceInfo
import io.dcloud.uniapp.extapi.getElementById as uni_getElementById
import io.dcloud.uniapp.extapi.getImageInfo as uni_getImageInfo
import io.dcloud.uniapp.extapi.getLocation as uni_getLocation
import io.dcloud.uniapp.extapi.getSystemInfo as uni_getSystemInfo
import io.dcloud.uniapp.extapi.installApk as uni_installApk
import io.dcloud.uniapp.extapi.saveImageToPhotosAlbum as uni_saveImageToPhotosAlbum
import io.dcloud.uniapp.extapi.shareWithSystem as uni_shareWithSystem
import io.dcloud.uniapp.extapi.showActionSheet as uni_showActionSheet
import io.dcloud.uniapp.extapi.showModal as uni_showModal
import io.dcloud.uniapp.extapi.showToast as uni_showToast
open class GenPagesIndexIndex : BasePage {
    constructor(__ins: ComponentInternalInstance) : super(__ins) {
        onReady(fun() {
            fs.readFile(ReadFileOptions(encoding = "utf-8", filePath = "static/uni.webview.1.5.5.js", success = fun(res: ReadFileSuccessResult){
                this.uniWebviewJs = res.data as String
            }
            , fail = fun(res: IFileSystemManagerFail){
                console.log("readFile失败", res)
            }
            ))
            getApp().globalData.webviewContext = uni_createWebviewContext("web-view", this)
            this.webviewElement = uni_getElementById("web-view") as UniWebViewElement
            this.webviewElement?.setAttribute("src", this.src)
            val deviceInfo = uni_getDeviceInfo(null)
            uni_getSystemInfo(GetSystemInfoOptions(success = fun(systemInfo){
                val stringDeviceInfo = JSON.stringify(UTSJSONObject.assign(UTSJSONObject(), deviceInfo, systemInfo))
                getApp().globalData.webviewContext?.evalJS("localStorage.setItem('deviceInfo', '" + stringDeviceInfo + "')")
            }
            ))
        }
        , __ins)
    }
    @Suppress("UNUSED_PARAMETER", "UNUSED_VARIABLE")
    override fun `$render`(): Any? {
        val _ctx = this
        val _cache = this.`$`.renderCache
        val _component_uni_navbar_lite = resolveEasyComponent("uni-navbar-lite", GenComponentsUniNavbarLiteUniNavbarLiteClass)
        return createElementVNode("view", utsMapOf("class" to "tuns-view-containter", "onTouchstart" to _ctx.touchStart, "onTouchmove" to _ctx.touchMove, "onTouchend" to _ctx.touchEnd), utsArrayOf(
            if (isTrue(_ctx.pageTitle)) {
                createVNode(_component_uni_navbar_lite, utsMapOf("key" to 0, "class" to "title-bar", "title" to _ctx.pageTitle), null, 8, utsArrayOf(
                    "title"
                ))
            } else {
                createCommentVNode("v-if", true)
            }
            ,
            createElementVNode("web-view", utsMapOf("id" to "web-view", "class" to "uni-flex-item", "style" to normalizeStyle(utsMapOf("pointer-events" to "auto")), "horizontalScrollBarAccess" to false, "verticalScrollBarAccess" to false, "onMessage" to _ctx.message, "onError" to _ctx.error, "onLoading" to _ctx.loading, "onLoad" to _ctx.load, "onDownload" to _ctx.download), null, 44, utsArrayOf(
                "onMessage",
                "onError",
                "onLoading",
                "onLoad",
                "onDownload"
            ))
        ), 40, utsArrayOf(
            "onTouchstart",
            "onTouchmove",
            "onTouchend"
        ))
    }
    open var src: String by `$data`
    open var webviewElement: UniWebViewElement? by `$data`
    open var pageTitle: String by `$data`
    open var touchStartX: Number by `$data`
    open var touchEndX: Number by `$data`
    open var uniWebviewJs: String by `$data`
    @Suppress("USELESS_CAST")
    override fun data(): Map<String, Any?> {
        return utsMapOf("src" to "http://192.168.1.57:8080", "webviewElement" to null as UniWebViewElement?, "pageTitle" to "", "touchStartX" to 0, "touchEndX" to 0, "uniWebviewJs" to "")
    }
    override fun `$initMethods`() {
        this.touchStart = fun(event: UniTouchEvent) {
            this.touchStartX = event.touches[0].pageX as Number
        }
        this.touchMove = fun(event: UniTouchEvent) {
            this.touchEndX = event.touches[0].pageX as Number
        }
        this.touchEnd = fun(event: UniTouchEvent) {
            console.log("touchEnd结束,起始x", this.touchStartX)
        }
        this.message = fun(event: UniWebViewMessageEvent) {
            val params = event.detail.data[0] as UTSJSONObject
            console.log("H5通信参数", JSON.stringify(params))
            val type = params["type"] as String
            val action = params["action"] as String
            val query = params["query"] as UTSJSONObject
            val tp = params["tp"] as String?
            if (type == "Invoke") {
                this.InvokeHanlder(action, query, tp)
            }
            if (type == "JsGetString") {
                this.InvokeJsString(action, query)
            }
        }
        this.error = fun(event: UniWebViewErrorEvent) {
            console.log("webview-error", JSON.stringify(event.detail))
            if (event.detail.errCode == 100002) {
                uni_showModal(ShowModalOptions(title = "提示", content = "页面加载失败，请确定是否重新加载，取消将会返回上一页", success = fun(res){
                    if (res.cancel) {
                        getApp().globalData.webviewContext?.back()
                    }
                    if (res.confirm) {
                        getApp().globalData.webviewContext?.back()
                    }
                }
                ))
            }
        }
        this.loading = fun(event: UniWebViewLoadingEvent) {
            console.log("webview-loading", JSON.stringify(event.detail))
        }
        this.load = fun(event: UniWebViewLoadEvent) {
            console.log("webview-load", JSON.stringify(event.detail))
            this.pageTitle = ""
            if (!event.detail.src.includes("wap.tuns.com.cn") && !event.detail.src.includes("192.168")) {
                getApp().globalData.webviewContext?.evalJS(this.uniWebviewJs + jsGetTitle)
            }
            getApp().globalData.webviewContext?.evalJS(this.uniWebviewJs + jsLongPressImg)
        }
        this.download = fun(event: UniWebViewDownloadEvent) {
            console.log("webview-download", JSON.stringify(event.detail))
            uni_showModal(ShowModalOptions(content = "下载链接: " + event.detail.url + "\n文件大小: " + event.detail.contentLength / 1024 + "KB", showCancel = false))
        }
    }
    open lateinit var touchStart: (event: UniTouchEvent) -> Unit
    open lateinit var touchMove: (event: UniTouchEvent) -> Unit
    open lateinit var touchEnd: (event: UniTouchEvent) -> Unit
    open lateinit var message: (event: UniWebViewMessageEvent) -> Unit
    open fun InvokeHanlder(action: String, query: UTSJSONObject = UTSJSONObject(), tp: String?) {
        when (action) {
            "appUpdate" -> 
                {
                    val res = uni_downloadFile(DownloadFileOptions(url = query["url"] as String, success = fun(res){
                        uni_installApk(InstallApkOptions(filePath = res.tempFilePath))
                    }
                    ))
                    res.onProgressUpdate(fun(result: OnProgressDownloadResult){
                        getApp().globalData.webviewContext?.evalJS("InvokeOnProgress" + tp + "(" + JSON.stringify(result) + ")")
                    }
                    )
                }
            "getLocation" -> 
                uni_getLocation(GetLocationOptions(success = fun(res){
                    getApp().globalData.webviewContext?.evalJS("InvokeSuccess" + tp + "(" + JSON.stringify(res) + ")")
                }
                ))
            else -> 
                {}
        }
    }
    open fun InvokeJsString(action: String, query: UTSJSONObject = UTSJSONObject()) {
        when (action) {
            "getPageTitle" -> 
                this.pageTitle = query["pageTitle"] as String
            "longPressImg" -> 
                {
                    val src = query["src"] as String
                    val originFilename = query["filename"] as Any
                    val mimeType = src.split(",")[0].split(":")[1].split(";")[0].split("/")[1]
                    var filename = ""
                    if (originFilename === "") {
                        filename = "" + Date.now() + "." + mimeType
                    }
                    console.log("filename", filename)
                    uni_showActionSheet(ShowActionSheetOptions(itemList = utsArrayOf(
                        "保存到相册",
                        "分享到微信"
                    ), success = fun(action: ShowActionSheetSuccess){
                        val isBase64 = src.includes("data:image/")
                        val actionClick = fun(tapIndex: Number, path: String){
                            if (tapIndex == 0) {
                                uni_saveImageToPhotosAlbum(SaveImageToPhotosAlbumOptions(filePath = path, success = fun(_){
                                    uni_showToast(ShowToastOptions(title = "已保存到手机相册", position = "bottom"))
                                }
                                ))
                            }
                            if (tapIndex == 1) {
                                uni_shareWithSystem(ShareWithSystemOptions(type = "image", imageUrl = path))
                            }
                        }
                        if (isBase64) {
                            val base64 = src.replace(UTSRegExp("^data:image\\/\\w+;base64,", ""), "")
                            val filePath = "" + uni_env.USER_DATA_PATH + "/temp_" + filename
                            val buffer = uni_base64ToArrayBuffer(base64)
                            console.log(filePath)
                            fs.writeFile(WriteFileOptions(encoding = "base64", filePath = filePath, data = buffer, success = fun(res){
                                actionClick(action.tapIndex, filePath)
                            }))
                        } else {
                            uni_getImageInfo(GetImageInfoOptions(src = src, success = fun(imgInfo: GetImageInfoSuccess){
                                val path = imgInfo.path as String
                                actionClick(action.tapIndex, path)
                            }
                            ))
                        }
                    }
                    ))
                }
            else -> 
                {}
        }
    }
    open lateinit var error: (event: UniWebViewErrorEvent) -> Unit
    open lateinit var loading: (event: UniWebViewLoadingEvent) -> Unit
    open lateinit var load: (event: UniWebViewLoadEvent) -> Unit
    open lateinit var download: (event: UniWebViewDownloadEvent) -> Unit
    companion object {
        val styles: Map<String, Map<String, Map<String, Any>>> by lazy {
            normalizeCssStyles(utsArrayOf(
                styles0
            ), utsArrayOf(
                GenApp.styles
            ))
        }
        val styles0: Map<String, Map<String, Map<String, Any>>>
            get() {
                return utsMapOf("tuns-view-containter" to padStyleMapOf(utsMapOf("display" to "flex", "flexDirection" to "column", "height" to "100%", "width" to "100%", "overflow" to "hidden")), "title-bar" to padStyleMapOf(utsMapOf("flexShrink" to 0)), "uni-flex-item" to padStyleMapOf(utsMapOf("flex" to 1)))
            }
        var inheritAttrs = true
        var inject: Map<String, Map<String, Any?>> = utsMapOf()
        var emits: Map<String, Any?> = utsMapOf()
        var props = normalizePropsOptions(utsMapOf())
        var propsNeedCastKeys: UTSArray<String> = utsArrayOf()
        var components: Map<String, CreateVueComponent> = utsMapOf()
    }
}
